package cn.xspace.wnx.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;

import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import com.xspace.android.xafcommon.util.RequestConstant;
import cn.xspace.library.util.Tools;
import com.xspace.android.xafcommon.view.RoundAngleImageView;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.SelectDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xspace.app.view.TitleBar;
import cn.xspace.wnx.R;
import cn.xspace.wnx.db.NoticeDao;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.wnx.util.Navigator;
import com.xspace.android.xafcommon.util.T;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Created by liuchen on 2016/11/15.
 * 机构信息页面
 */

public class OrganizationInfoActivity extends BaseActivity {
    private static final String TAG = OrganizationInfoActivity.class.getSimpleName();

    private TitleBar mTitle_bar;
    private ImageView mImg_logo;
    private TextView mTxt_org_name;
    private TextView mTxt_org_introduce;
    private TextView mTxt_org_phone;
    private TextView mTxt_org_address;
    private RelativeLayout mRelative_org_tel;
    private RelativeLayout mRelative_org_post;

    private RelativeLayout mRelative_look_history_message;
    private RelativeLayout mRelative_message_clear;
    private RelativeLayout mRelative_dept_into;

    private String dept_id = "";
    private String searchId = "";
    private String searchPhone = "";

    private OrgDeptUserBean mBean;

    private List<String> phoneMode;
    private String[] phoneModeArray;

    @Override
    protected void getIntentData() {
        super.getIntentData();

        Bundle bundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
        if (bundle != null) { //传递数据进来的是查询别人的微农信消息
            dept_id = bundle.getString(RequestConstant.KEY_ORG_ID);
            searchId = bundle.getString(RequestConstant.KEY_SEARCH_ID); //要查看某个人的历史消息需要该字段
            searchPhone = bundle.getString(RequestConstant.KEY_SEARCH_PHONE);
        } else { //如果没有传递数据则只需要查自己的就可以了
            dept_id = getIntent().getStringExtra(RequestConstant.KEY_ORG_ID);
        }
        LogUtil.d(TAG, "wubaojie>>>" + "getIntentData: dept_id :" + dept_id + " searchId : " + searchId + " " +
                "searchPhone :" + searchPhone);
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_organization_info);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mTitle_bar = (cn.xspace.app.view.TitleBar) findViewById(R.id.title_bar);
        mImg_logo = (RoundAngleImageView) findViewById(R.id.img_logo);
        mTxt_org_name = (TextView) findViewById(R.id.txt_org_name);
        mTxt_org_introduce = (TextView) findViewById(R.id.txt_org_introduce);
        mTxt_org_phone = (TextView) findViewById(R.id.txt_org_phone);
        mTxt_org_address = (TextView) findViewById(R.id.txt_org_address);
        mRelative_org_tel = (RelativeLayout) findViewById(R.id.relative_org_tel);
        mRelative_org_post = (RelativeLayout) findViewById(R.id.relative_org_post);
        mRelative_look_history_message = (RelativeLayout) findViewById(R.id.relative_look_history_message);
        mRelative_message_clear = (RelativeLayout) findViewById(R.id.relative_message_clear);
        mRelative_dept_into = (RelativeLayout) findViewById(R.id.relative_dept_into);
    }

    @Override
    protected void initData() {
        super.initData();
        phoneModeArray = getResources().getStringArray(R.array.phone_mode);
        String user_id = MyInfoUtil.getMyUserid(mContext);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(RequestConstant.KEY_ORG_ID, dept_id);
        dataMap.put(RequestConstant.KEY_USER_ID, user_id);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.QUEY_DEPT_BASE_INFO, dataMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, OrgDeptUserBean>() {
                    @Override
                    public OrgDeptUserBean call(BaseReturnBean baseReturnBean) {
                        LogUtil.d(baseReturnBean.data);
                        OrgDeptUserBean bean = null;
                        try {
                            JSONObject json = new JSONObject(baseReturnBean.data);
                            bean = new OrgDeptUserBean();
                            bean.dept_id = json.optString("dept_id");
                            bean.dept_name = json.optString("dept_name");
                            bean.logo = json.optString("dept_logo");
                            bean.user_mobile = json.optString("dept_mobile");
                            bean.dept_address = json.optString("dept_address");
                            bean.dept_desc = json.optString("dept_desc");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {

                        }
                        return bean;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OrgDeptUserBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(OrgDeptUserBean userBean) {
                        LogUtil.d(userBean.toString());
                        if (userBean == null) {
                            T.showShort(mContext, R.string.network_error);
                            return;
                        }
                        mBean = userBean;

                        fillView(userBean);
                    }
                }));
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mRelative_org_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isMobile(mBean.user_mobile)) {
                        LogUtil.e(TAG, "wubaojie>>>" + "onClick: 是手机号");
                        phoneMode = Arrays.asList(phoneModeArray);
                    } else {
                        LogUtil.e(TAG, "wubaojie>>>" + "onClick: 不是手机号");
                        phoneMode = new ArrayList<>();
                        phoneMode.add(phoneModeArray[0]);
                        phoneMode.add(phoneModeArray[2]);
                    }
                    if (!TextUtils.isEmpty(mBean.user_mobile)) {
                        showDialog();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        mRelative_org_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null) {
                    Navigator.startOrgPostInfoActivity(mContext, dept_id);
                }
            }
        });

        //查看历史消息
        mRelative_look_history_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null) {
                    Bundle mBundle = new Bundle();
                    mBundle.putString(BldNavigation.SENDER_ID, mBean.dept_id);
                    mBundle.putString(BldNavigation.SENDER_NAME, mBean.dept_name);
//                mBundle.putString(RequestConstant.KEY_SEARCH_ID, searchId);
//                mBundle.putString(RequestConstant.KEY_SEARCH_PHONE, searchPhone);
                    mBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.WNX_MSG.toNumber());
                    mBundle.putBoolean(BldNavigation.LOOK_HISTORY, true);
                    Navigator.startWnxListActivity(mContext, mBundle);
                }
            }
        });
        //清空消息记录
        mRelative_message_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBean != null) {
                    DialogHelp.getConfirmDialog(mContext,
                            getResources().getString(R.string.txt_message_clear),
                            getResources().getString(R.string.chat_message_clear_confirm),
                            getResources().getString(R.string.think_again_and_again),
                            getResources().getString(R.string.txt_clear),
                            null,
                            new ButtonClickListener() {
                                @Override
                                public void buttonClick(View view) {
                                    //清空本地消息
                                    registerSubscription(NoticeDao.getInstance().getData().deleteAllWnxNoticeByDepId
                                            (dept_id)
                                            .observeOn(Schedulers.io())
                                            .subscribeOn(AndroidSchedulers.mainThread())
                                            .doOnNext(new Action1<String>() {
                                                @Override
                                                public void call(String s) {

                                                }
                                            })
                                            .subscribe(new Subscriber<String>() {
                                                @Override
                                                public void onCompleted() {

                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    e.printStackTrace();
                                                }

                                                @Override
                                                public void onNext(String s) {
                                                    T.showShort(mContext, "清空成功");
                                                    Map<String, Object> messageMap = new HashMap<>();
                                                    messageMap.put(EventBusConstant.TYPE, EventBusConstant
                                                            .CLEAR_WNX_OR_NOTICE);
                                                    messageMap.put(EventBusConstant.ACTION_VALUE, mBean.logo);
                                                    EventBus.getDefault().post(messageMap);
                                                }
                                            }));
                                }
                            }
                    ).show();
                }
            }
        });

        mTitle_bar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //进入机构
        mRelative_dept_into.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                senderId = mBundle.getString(Navigator.SENDER_ID);
//                senderName = mBundle.getString(Navigator.SENDER_NAME);
//                msgType = mBundle.getInt(Navigator.CHAT_TYPE, MessageEntity.MsgType.NOTICE.toNumber());
                if (mBean != null) {
                    Bundle mBundle = new Bundle();
                    mBundle.putString(BldNavigation.SENDER_ID, mBean.dept_id);
                    mBundle.putString(BldNavigation.SENDER_NAME, mBean.dept_name);
                    mBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.WNX_MSG.toNumber());
                    Navigator.startWnxListActivity(mContext, mBundle);
                }
            }
        });
    }

    /**
     * 判断号码是否是手机号
     *
     * @param mobile
     * @return
     */
    public boolean isMobile(String mobile) {
        Pattern pattern = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher matcher = pattern.matcher(mobile);
        return matcher.matches();
    }

    /**
     * 点击电话时弹出的对话框
     */
    private void showDialog() {
        final SelectDialog.Builder builder = new SelectDialog.Builder(this);
        final String[] arr = (String[]) phoneMode.toArray(new String[phoneMode.size()]);
        builder.setSingleChoiceItems(arr, new SelectDialog.ISelectItemListener() {
            @Override
            public void selectItemClick(int position) {
                String operation = phoneMode.get(position);
                if (TextUtils.equals(operation, phoneModeArray[0])) { //拨打电话
                    Tools.getCallByPhone(OrganizationInfoActivity.this, mBean.user_mobile);
                } else if (TextUtils.equals(operation, phoneModeArray[1])) { //发送短信
                    Tools.sendMessageByPhone(OrganizationInfoActivity.this, mBean.user_mobile);
                } else if (TextUtils.equals(operation, phoneModeArray[2])) { //取消
                    builder.dismiss();
                }
            }
        });
        builder.show();
    }

//    Subscriber<OrgDeptUserBean> orgSub = ;

    private void fillView(OrgDeptUserBean bean) {
        mTxt_org_name.setText(bean.dept_name);
        mTxt_org_introduce.setText(TextUtils.isEmpty(bean.dept_desc) ? "暂无简介" : bean.dept_desc);
        mTxt_org_phone.setText(TextUtils.isEmpty(bean.user_mobile) ? "暂无" : bean.user_mobile);
        mTxt_org_address.setText(TextUtils.isEmpty(bean.dept_address) ? "暂无" : bean.dept_address);
        if (TextUtils.isEmpty(bean.logo)) {
            mImg_logo.setImageResource(R.drawable.icon_org_logo_default);
        } else {
            Picasso.with(mContext)
                    .load(bean.logo)
                    .placeholder(R.drawable.icon_org_logo_default)
                    .error(R.drawable.icon_org_logo_default)
                    .into(mImg_logo);
        }
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        super.onEventMainThread(inParam);
    }
}
